import { useFuncStore } from '@/store/func-store';
import { useFuncConfig } from '@/hooks/use-func-config';
import { Hooks, Data } from '@jecloud/ui';
import { decode, encode, clone, isNotEmpty, getDDCache, cloneDeep } from '@jecloud/utils';
import { reactive, watch, toRaw, ref } from 'vue';

export function useFormField({ props, context }) {
  const funcStore = useFuncStore();
  // 表单数据
  const formState = Hooks.useModelValue({ props, context, key: 'recordData' });
  // 表格字段，处理字段是json数组
  const tableFieldKeys = ['RESOURCEFIELD_UNITLISTTPL'];
  const tableFields = reactive({});
  const dicType = ref('LIST');
  tableFieldKeys.forEach((key) => {
    watch(
      () => formState.value[key],
      (value) => {
        tableFields[key] = (value && decode(value)) ?? [];
      },
      { immediate: true },
    );
    watch(
      () => tableFields[key],
      (value) => {
        formState.value[key] = (value && encode(value)) ?? '';
      },
      // { deep: true },
    );
  });

  /**
   * 添加数据
   * @param {*} param0
   */
  const addTableFieldValue = ({ key, data }) => {
    const tableData = clone(toRaw(tableFields[key])) || [];
    tableData.push(data);
    tableFields[key] = tableData;
  };
  /**
   * 删除数据
   * @param {*} param0
   */
  const removeTableFieldValue = ({ key, index }) => {
    const tableData = clone(toRaw(tableFields[key])) || [];
    tableData.splice(index, 1);
    tableFields[key] = tableData;
  };
  /**
   * 获取table字段的值
   * @returns
   */
  const getTableFieldValues = () => {
    const values = {};
    tableFieldKeys.forEach((key) => {
      values[key] = encode(tableFields[key]);
    });
    return values;
  };
  /**
   * 打开列表字段配置
   */
  const showColumnConfig = ({ source = '', props = {} }) => {
    const { showFuncConfig } = useFuncConfig();
    showFuncConfig({
      key: 'FuncListField',
      funcId: formState.value.RESOURCEFIELD_FUNCINFO_ID,
      code: formState.value.RESOURCEFIELD_CODE,
      source,
      props,
    });
  };
  // sql字典过滤条件
  const dicGridStore = Data.Store.useGridStore({ data: [] });
  const addDicColumn = () => {
    dicGridStore.insert({ code: '', value: '' }, -1);
  };
  const deleteDicColumn = (row) => {
    dicGridStore.remove(row);
  };
  watch(
    () => formState.value.JE_CORE_RESOURCEFIELD_ID,
    () => {
      const value = formState.value.RESOURCEFIELD_DD_CUSTOMER_VARIABLES;
      if (isNotEmpty(value)) {
        dicGridStore.loadData(decode(value));
      } else {
        dicGridStore.loadData([]);
      }
    },
    { immediate: true },
  );
  watch(
    () => dicGridStore.data,
    (value) => {
      const gridData = cloneDeep(value);
      const strData = [];
      gridData.forEach((item) => {
        strData.push({ code: item.code, value: item.value });
      });
      formState.value.RESOURCEFIELD_DD_CUSTOMER_VARIABLES =
        strData.length > 0 ? encode(strData) : '';
    },
    { deep: true },
  );
  // 确定配置的字典类型
  watch(
    () => formState.value.RESOURCEFIELD_CONFIGINFO,
    (value) => {
      if (isNotEmpty(value)) {
        const ddCode = value.split(',')[0];
        const ddObj = getDDCache(ddCode);
        if (isNotEmpty(ddObj) && ddObj.type) {
          if (
            dicType.value != ddObj.type &&
            ['LIST', 'TREE', 'DYNA_TREE'].indexOf(ddObj.type) != -1
          ) {
            formState.value.RESOURCEFIELD_DD_CUSTOMER_VARIABLES = '';
            dicGridStore.loadData([]);
          }
          dicType.value = ddObj.type;
        }
      }
    },
    { immediate: true },
  );
  return {
    funcStore,
    formState,
    tableFields,
    showColumnConfig,
    getTableFieldValues,
    addTableFieldValue,
    removeTableFieldValue,
    dicGridStore,
    addDicColumn,
    deleteDicColumn,
    dicType,
  };
}
